package com.situ.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/lastAccessTime")
public class LastAccessTimeServlet extends HttpServlet{
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 每次访问记录当前访问时间，设置到Cookie里面，不管是不是第一次访问
		// 当前的日期
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss");
		String time = simpleDateFormat.format(date);
		Cookie cookie = new Cookie("lastAccessTime", time);
		resp.addCookie(cookie);
		
		// 获取Cookie信息，显示到页面
		Cookie[] cookies = req.getCookies();
		String lastAccessTime = "";
		if (cookies != null) {
			for (Cookie coo : cookies) {
				// lastAccessTime : 时间
				if ("lastAccessTime".equals(coo.getName())) {
					lastAccessTime = coo.getValue();
				}
			}
		}
		
		// 显示到页面
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		if ("".equals(lastAccessTime)) {
			writer.println("您是第一次访问");
		} else {
			writer.println("您上次访问的时间： " + lastAccessTime);
		}
		writer.close();
	}
	
	public static void main(String[] args) {
		Date date = new Date();
		System.out.println(date);// Fri Aug 21 11:49:17 CST 2020
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String time = simpleDateFormat.format(date);
		System.out.println(time);// 2020-08-21 11:51:44
	}
}
